package com.edu.user.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.UpdateById;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.user.domain.dto.LoginFormDTO;
import com.edu.user.domain.dto.UserUpdateDTO;
import com.edu.user.domain.po.User;
import com.edu.user.domain.vo.DoctorInfoVO;
import com.edu.user.domain.vo.DoctorVO;
import com.edu.user.domain.vo.UserLoginVO;
import com.edu.user.mapper.UserMapper;
import com.edu.user.service.DoctorService;
import com.edu.user.service.UserService;
import com.edu.user.utils.*;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import javax.sound.midi.Soundbank;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.edu.user.utils.RedisConstants.*;


@RequiredArgsConstructor
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    UserMapper userMapper;


    @Override
    public Result login(LoginFormDTO loginForm) {
        //1.校验手机号
        String phone = loginForm.getPhone();
        if (!RegexUtils.isPhoneInvalid(phone)){
            //2.如果不符合，返回错误信息
            return Result.error("手机号格式错误");
        }
        //2.校验验证码
        String code = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY+phone);
        String code1 = loginForm.getCode();
        if(code==null||!code.toString().equals(code1)){
            //3.不一致，报错
            return Result.error("验证码错误");
        }

        //4.一致，根据手机号查询用户 select *from tb_user where phone=?
        User user = query().eq("phone", phone).one();
        //5判断用户是否存在
        if(user==null){
            //6不存在，创建新用户并保存
            user=createUserWithPhone(phone);
        }

        // 7.保存用户信息到redis中

        // 7.1将User对象转成Hash存储

        Map<String, Object> map = BeanUtil.beanToMap(user, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> {
                            if (fieldValue != null) {
                                return fieldValue.toString();
                            } else {
                                return null; // 或者进行其他处理
                            }
                        })
        );

       /* Map<String, Object> map = BeanUtil.beanToMap(userDTO);
        map.forEach((key,value)->{if(null!=value)map.put(key,String.valueOf(value));});*/
        // 7.2生成token，作为登录令牌
        String token = JwtUtil.genToken(map);

        // 7.3存储
        String token2=LOGIN_USER_KEY+token;

        stringRedisTemplate.opsForValue().set(token2,token2);

        // 7.4设置token有效期
        stringRedisTemplate.expire(token2,LOGIN_USER_TTL, TimeUnit.MINUTES);
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setUserId(Math.toIntExact(user.getId()));
        userLoginVO.setToken(token);
        userLoginVO.setRole(user.getRole());
        userLoginVO.setName(user.getName());

        // 8返回
        return Result.success(userLoginVO);

    }

    @Override
    public Result<String> updateUserProfile(UserUpdateDTO updatedUser) {
        System.out.println(updatedUser);
        User currentUser = ThreadLocalUtil.get();
       if(currentUser==null){
           return Result.error("请先登录");
       }
        // 检查邮箱是否重复
        if (StringUtils.hasText(updatedUser.getEmail()) && emailExists(updatedUser.getEmail(), currentUser.getId())) {
            return Result.error("邮箱已被使用");
        }

        User userToUpdate = new User();
        BeanUtils.copyProperties(updatedUser, userToUpdate);
        userToUpdate.setId(currentUser.getId());
        // 更新数据库
        updateById(userToUpdate);

        // 更新 Redis
        Map<String, Object> map = BeanUtil.beanToMap(userToUpdate, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> {
                            if (fieldValue != null) {
                                return fieldValue.toString();
                            } else {
                                return null;
                            }
                        })
        );

        // 生成 token，作为登录令牌
        String token = JwtUtil.genToken(map);

        // 存储 token
        String tokenKey = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForValue().set(tokenKey, token);
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);

        return Result.success(token);

    }

    @Override
    public String updateUserName(Long userId, String newName) {
        User user = userMapper.selectById(userId);
        if (user != null) {
            user.setName(newName);
            userMapper.updateById(user);

            // 更新 Redis
            Map<String, Object> map = BeanUtil.beanToMap(user, new HashMap<>(),
                    CopyOptions.create()
                            .setIgnoreNullValue(true)
                            .setFieldValueEditor((fieldName, fieldValue) -> {
                                if (fieldValue != null) {
                                    return fieldValue.toString();
                                } else {
                                    return null;
                                }
                            })
            );

            // 生成 token，作为登录令牌
            String token = JwtUtil.genToken(map);

            // 存储 token
            String tokenKey = LOGIN_USER_KEY + token;
            stringRedisTemplate.opsForValue().set(tokenKey, token);
            stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
            return token;
        } else {
            return null;
          //  throw new RuntimeException("找不到用户信息，更新用户名失败");
        }
    }

//    @Override
//    public DoctorInfoVO getDoctorInfoById(Long userId) {
//        User user = getById(userId);
//        DoctorInfoVO doctorInfoVO = BeanUtils.copyProperties(user, DoctorInfoVO.class);
//        DoctorVO detailById = doctorService.getDetailById(Math.toIntExact(userId));
//        BeanUtils.copyProperties(detailById,doctorInfoVO);
//        return doctorInfoVO;
//    }

    // 检查邮箱是否重复
    private boolean emailExists(String email, Long userId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email).ne("id", userId);
        int count = (int) count(queryWrapper);
        return count > 0;
    }


    private User createUserWithPhone(String phone) {
        //1.创建用户
        User user = new User();
        user.setPhone(phone);
        user.setRole("patient");
        user.setName( "user_" + RandomUtil.randomString(10));
        //2.保存用户
        save(user);
        return user;
    }




}

